package edu.syr.iis.web.util;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import edu.syr.iis.web.model.AnnotationSession;
import edu.syr.iis.web.model.AnnotationSessionManager;
import edu.syr.iis.web.model.User;

public class SecurityManager {
	
	AnnotationSessionManager annotationSessionManager = new AnnotationSessionManager();
	
		
	public void singIn(HttpServletRequest request, User user)
	{
		AnnotationSession as = annotationSessionManager.getNewAnnotationSession(user);
		
		request.getSession(true).setAttribute(Key.SESSION, as);
		request.getSession(true).setAttribute(Key.USER, user);		
	}

	public AnnotationSession signOut(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		AnnotationSession annotationSession = (AnnotationSession) session.getAttribute(Key.SESSION);
		
		annotationSession.setEndDateTime(new Date());
		annotationSessionManager.saveAnnotationSession(annotationSession);
		
		session.setAttribute(Key.SESSION, null);
		session.setAttribute(Key.USER, null);
		
		return annotationSession;
	}
	
	public void updateAnnotationSession(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		AnnotationSession annotationSession = (AnnotationSession) session.getAttribute(Key.SESSION);

		annotationSession.setEndDateTime(new Date());
		annotationSessionManager.saveAnnotationSession(annotationSession);			
	}
	
	
	public User getUser(HttpServletRequest request)
	{
		return (User) request.getSession(true).getAttribute(Key.USER);
	}

	public AnnotationSessionManager getAnnotationSessionManager() {
		return annotationSessionManager;
	}

	public void setAnnotationSessionManager(
			AnnotationSessionManager annotationSessionManager) {
		this.annotationSessionManager = annotationSessionManager;
	}
	
	
}
